#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import rospy
from mqtt_integration.msg import TimeInfo
from datetime import datetime, timedelta
import time
import signal
import sys

# 全局变量
start_time = time.time()

def main():
    global start_time
    
    # 初始化ROS节点
    rospy.init_node('time_publisher')
    pub = rospy.Publisher('time_info', TimeInfo, queue_size=10)
    
    rate = rospy.Rate(1)  # 1 Hz
    
    def signal_handler(sig, frame):
        print("正在停止...")
        sys.exit(0)

    signal.signal(signal.SIGINT, signal_handler)

    while not rospy.is_shutdown():
        current_time = datetime.now()
        elapsed_time = time.time() - start_time
        
        # 格式化为16进制字符串
        current_time_hex = current_time.strftime("%Y%m%d%H%M%S")
        
        # 将经过时间转换为小时:分钟:秒格式
        elapsed_time_td = timedelta(seconds=int(elapsed_time))
        elapsed_time_str = str(elapsed_time_td)
        
        # 创建消息
        time_info_msg = TimeInfo()
        time_info_msg.current_time = current_time_hex
        time_info_msg.elapsed_time = elapsed_time_str
        
        # 发布消息
        pub.publish(time_info_msg)
        # print(f"已发布当前时间: {time_info_msg.current_time}, 经过时长: {time_info_msg.elapsed_time}")
        
        rate.sleep()

if __name__ == "__main__":
    main()
